// 创建邻接表

class HNode {
    /**
     * 头节点信息
     * @param {*} data 节点数据
     * @param {*} firstEdge 指向单链表的头节点
     */
    constructor (data, firstEdge) {
        this.data = data
        this.firstEdge = firstEdge
    }
}

class CNode {
    /**
     * 单链表节点
     * @param {*} index 邻接点在数组中（顶点表）的位置
     * @param {*} weight 边的代价
     * @param {*} nextCNode 下一个依附于 vi 的单链表
     */
    constructor (index, weight, nextCNode) {
        this.index = index
        this.weight = weight
        this.nextCNode = nextCNode
    }   
}

class MGraph {
    /**
     * 邻接表对象
     * @param {*} nodeList 节点集
     * @param {*} edgeList 边集
     * @param {*} type 1 无向图， 2 有向图
     */
    constructor (nodeList, edgeList, type) {
        this.data = []
        for (let i = 0; i < nodeList.length; i++) {
            const h = new HNode()
            h.data = nodeList[i]
            h.firstEdge = null
            this.data[i] = h
        }
        for (let edge of edgeList) {
            let c;
            // 前插到单链表中
            if (type === '1') {
                c = new CNode()
                c.weight = edge.weight
                c.index = edge.j
                c.nextCNode = this.data[edge.i].firstEdge
                this.data[edge.i].firstEdge = c
                c = new CNode()
                c.weight = edge.weight
                c.index = edge.i
                c.nextCNode = this.data[edge.j].firstEdge
                this.data[edge.j].firstEdge = c
            } else {
                c = new CNode()
                c.weight = edge.weight
                c.index = edge.j
                c.nextCNode = this.data[edge.i].firstEdge
                this.data[edge.i].firstEdge = c
            }
        }
    }
}

// const g = new MGraph(['A', 'B', 'C', 'D'], [{i: 0, j: 1, wei: 10}, {i: 0, j: 3, wei: 30}, {i: 1, j: 3, wei: 20}, {i: 3, j: 2, wei: 40}, {i: 2, j: 0, wei: 50}], '2')
// console.log(JSON.stringify(g))


module.exports = MGraph